<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>单例模式</title>
</head>
<body>
  <script>
    // 第一个次创建时， 将实例保存在函数上， 下次再new时， 直接返回第一次保存的
    function Singleton1(name) {
      if (Singleton1._instance) {
        return Singleton1._instance
      }

      this.name = name
      Singleton1._instance = this
    }

    const s1 = new Singleton1('s1')
    const s2 = new Singleton1('s2')
    // console.log(s1===s2) // true
  </script>

  <script>
    function Singleton2 (name) {
      this.name = name
    }

    // 通过构造函数的静态方法来实现
      // 第一次调用： 创建实例， 保存到在实例上， 返回它
      // 再次调用： 直接返回第一次保存的
    Singleton2.getInstance = function (name) {
      if (this._instance) {
        return this._instance
      }
      return (this._instance = new Singleton2(name))
    }

    const a = Singleton2.getInstance("a")
    const b = Singleton2.getInstance("b")
    // console.log(a===b)
    // console.log(a.name, b.name)
  </script>

  <script>
    // 通用的工具函数
    function singleton (Type) {
      let instance
      return function(...args) {
        if (instance) return instance
        return instance = new Type(...args)
      }
    }

    function Person(name, age) {
      this.name = name
      this.age = age
    }

    function Student(name) {
      this.name = name
    }

    const PeopleSingleton = singleton(Person)
    const p1 = new PeopleSingleton('A', 12)
    const p2 = new PeopleSingleton('B', 13)

    const s  = new singleton(Student)('A')
    const s4  = new singleton(Student)('B')

    // console.log(p1===p2)
  </script>
</body>
</html>